<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #908;
        }
    </style>
</head>
<body>
    <div id="result"></div>
    <script>
        const result = document.querySelector('#result')
        // 绑定键盘按下事件
        window.onkeydown = function(){
            // 1.创建对象
            const xhr = new XMLHttpRequest()
            // 设置响应体数据的类型
            xhr.responseType = 'json'
            // 2.设置请求类型和url
            xhr.open('GET','http://127.0.0.1:8000/json-server')
            // 3.发送请求
            xhr.send()
            // 4.事件绑定
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status>=200&&xhr.status<300){
                        // 手动对数据进行转换
                        // let data = JSON.parse(xhr.response)
                        // result.innerHTML = data.name

                        // 自动转化。借助xhr.responseType = 'json'
                        console.log(xhr.response);
                        result.innerHTML = xhr.response.name
                        
                    }
                }
            }

        }
    </script>
</body>
</html>